const http = require('http');
const querystring = require('querystring');
const config = require('./config');
const log = require('./log')
const api = require('./tk_api');
const errCode = require('./code');
const ipc = {
    login: {name: 'resetLogin'},
    start: {name: 'startApplf'}
};
var cookies, ad = '';

process.on('message', function (m) {
    switch (m.name) {
        case 'getcookies':
            cookies = m.value;
            break;
        case 'applfCommins':
            // var i=0;
            // setInterval(function(){
            //     i++;
            //    process.send({code:errCode.applfLoding,data:{name:'测试的商品',status:'yes'}});
            // },2000);
            if (!cookies) {
                ad = m.value.ad;
                cookies = m.value.cookie;
                getGoodsList();
            }
            break;
        case 'closed' :
            process.exit(2);
            break;
        default:
            console.log(m);
    }

});
process.on('exit', function (code) {

});


function getGoods(url) {
    if (!cookies) {
        process.send(ipc.login);
        process.exit(1);
    }
    url = 'https://item.taobao.com/item.htm?spm=a219t.7900221/21.1998910419.d9a1dac8enzjh.rWn4AD&id=545139562165';
    var id = url.match(/id=(\d+)/);
    if (!id) {
        return false;
    }
    api.setCallbackFunc(applf);
    $code = api.start(cookies, url, ad);
    // api.searchRate(cookies, url);
}

function getGoodsList() {
    getGoods();return;
    var reqData = querystring.stringify({
        t: date.getTime(),
        _tb_token_: cookies._tb_token_
    });
    var type = 'POST';
    var header = {
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
    };
    if (type === 'POST') {
        header['Content-Length'] = Buffer.byteLength(reqData)
    }
    var post_options = {
        host: config.goods_host,
        port: config.goods_port,
        path: config.goods_path,
        method: type,
        headers: header
    };
    var post_req = http.request(post_options, function (response) {
        var responseText = [];
        var size = 0;
        response.on('data', function (data) {
            responseText.push(data);
            size += data.length;
        });
        response.on('error', function (e) {
            // help.showErr(e.message);
        });
        response.on('end', function () {
            responseText = Buffer.concat(responseText, size);
            try {
                var goods = JSON.parse(responseText.toString());
                if (goods.ok) {
                    getGoods(url);
                }
            } catch (err) {
                log.createLog(err, 'getGoodsError.log');
                return false;
            }
        });
    });
    post_req.write(conf.arg);
    post_req.end();
}

//高佣申请回调函数
function applf(code, data) {
    if (!code) return false;
    var sendMsg=(data)=>{
        data = data || {};
        var msg = {
            code: code,
            data: data
        };
        this.process.send(msg);
    };
    switch (code) {
        case errCode.login :
            sendMsg();
            break;
        case errCode.reay_applf :
            sendMsg();
            break;
        case errCode.applfLoding:
            sendMsg(data);
            break;
        case errCode.convert:
            sendMsg(data);
            break;
        default:
            console.log(code, data);
            break;
    }
}
applf.prototype.process = process;
